package demo.orm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author : GuoFei
 * @date : 2019/1/22 10:30
 */
public class DBManage {

    public static void close(PreparedStatement preparedStatement,Connection connection){
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private static Logger log = LoggerFactory.getLogger(DBManage.class);

    private static MyConfiguration conf;
    static {
        Properties properties = new Properties();
        try {
            properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("properties/local/jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("读取数据库配置文件出错");
        }
        conf = new MyConfiguration();
        conf.setDriver(properties.getProperty("jdbc.driver"));
        conf.setPassword(properties.getProperty("jdbc.password"));
        conf.setPoPackage(properties.getProperty("pojo.package"));
        conf.setSrcPath(properties.getProperty("pojo.src.path"));
        conf.setUrl(properties.getProperty("jdbc.url"));
        conf.setUserName(properties.getProperty("jdbc.username"));
        conf.setUsingDB(properties.getProperty("jdbc.db"));
    }

    public static Connection getConn(){
        log.info("获取数据库链接");
        try {
            Class.forName(conf.getDriver());
            return DriverManager.getConnection(conf.getUrl(), conf.getUserName(), conf.getPassword());
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        log.error("获取数据库链接报错");
        return null;
    }

    public static MyConfiguration getConf(){
        return conf;
    }
}
